<template>
  <div class="candlestick-wrapper">
    <div class="chart-wrap">
      <div class="top-box">
        <Button type="primary" @click="createLine">生成曲线</Button>
      </div>
      <div class="bottom-box">
        <e-candlestick
          id="operateCandlestick"
          :chartData="rectTreeMapData"
          @q-click="candlestickClickHandle"
          @q-datazoom="candlestickDatazoom"
        />
      </div>
    </div>
    <Modal
      v-model="showMeterDayModel"
      class="meter-day-modal"
      title="一天抄表读数"
      @on-cancel="onMeterDayCancel"
      width="96%"
      :styles="{ top: '30px', height: '85%' }"
    >
      <div class="filter-wrap">
        <Button @click="submitData" type="primary">提交修改</Button>
        <Button @click="saveData" type="info">保存</Button>
      </div>
      <div class="chart-wrap">
        <echart-barline-marker
          id="zhexianday"
          :chartData="zhexianDayData"
          :options="eLineByDayOptions"
          @clickSeries="zhexianDayClickHandle"
          :markPointData="currentMarkData"
          @contextmenu="zhexianContextMenuSelectHandle"
        />
      </div>

      <div slot="footer">
        <Button @click="onMeterDayCancel" ghost>关闭</Button>
      </div>
    </Modal>
    <Modal
      key="zhexiantime"
      v-model="showMeterTimeModel"
      title="小时抄表读数"
      @on-cancel="onMeterTimeCancel"
      width="96%"
      :styles="{ top: '30px', height: '85%' }"
    >
      <e-line :modal="true" id="zhexiantime" :chartData="zhexianTimeData" />
      <div slot="footer">
        <Button @click="onMeterTimeCancel" ghost>关闭</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import dayjs from 'dayjs'
import { concat, each, last, merge, isEmpty } from 'lodash'
import { getCandlestickData, getElineByHours } from '@/api/gasConsumptionDetail'
import operateElineMixin from '@/mixins/operateEline'
import { eCandlestickOptions, eLineByDayOptions, eLineByTimeOptions } from './chartOptions/index'

export default {
  name: 'kxianAndBarlineMarker',
  mixins: [operateElineMixin],
  components: {
    ECandlestick: () => import('@/commons/charts/ECandlestick'),
    ELine: () => import('@/commons/charts/ELine'),
    EchartBarlineMarker: () => import('@/commons/charts/EchartBarlineMarker')
  },
  props: {
    options: {
      type: Object
    }
  },
  data() {
    return {
      showMeterDayModel: false,
      showMeterTimeModel: false,
      rectTreeMapData: {},
      zhexianDayData: null,
      zhexianTimeData: null,
      hasZhishuRequest: true,
      zhishuAddDate: null,
      currentMarkData: []
    }
  },
  computed: {
    eLineByDayOptions() {
      return eLineByDayOptions
    }
  },
  mounted() {
    const { month } = this.options
    this.zhishuAddDate = month
    this.getMonthData()
  },
  methods: {
    onMeterDayCancel() {
      this.showMeterDayModel = false
    },
    onMeterTimeCancel() {
      this.showMeterTimeModel = false
    },
    /**
     * @msg: 指数图缩放
     * @param {type}
     * @return:
     */
    candlestickDatazoom(data = {}, chart) {
      if (!this.hasZhishuRequest) return
      const { batch = [] } = data
      if (batch[0].start === 0 && batch[0].end === 100) {
        const retDate =
          this.zhishuAddDate &&
          dayjs(this.zhishuAddDate)
            .subtract(1, 'month')
            .format('YYYY-MM')

        this.zhishuAddDate = retDate
        this.$Spin.show({
          render: h => {
            return h('div', [
              h('Icon', {
                class: 'spin-icon-load',
                props: {
                  type: 'ios-loading',
                  size: 20
                }
              }),
              h('div', '图表生成中...')
            ])
          }
        })
        this.getMonthData()
      }
    },
    /**
     * @msg: 指数图数据
     * @param {type}
     * @return:
     */
    modifyRectTreeMapData(rawData = []) {
      let xAixisList = []
      let values = []
      const actualGas = []
      const markPointData = []
      each(rawData, item => {
        const [first, one, two, three, four, five] = item
        xAixisList.push(first)
        let color0 = '#ec0000'
        let borderColor0 = '#8A0000'
        let color = '#00da3c'
        let borderColor = '#008F28'
        const lastItem = last(item)
        if (lastItem) {
          color0 = '#ff9900'
          borderColor0 = '#ff9900'
          color = '#ff9900'
          borderColor = '#ff9900'
          markPointData.push({
            name: first,
            value: two,
            coord: [first, two],
            itemStyle: {
              color: '#ff9900'
            }
          })
        }
        if (five < 0) {
          color0 = '#ed141e'
          borderColor0 = '#ed141e'
          color = '#ed141e'
          borderColor = '#ed141e'
        }
        values.push({
          name: first,
          value: [one, two, four, three],
          itemStyle: {
            color,
            color0,
            borderColor,
            borderColor0
          }
        })
        actualGas.push(five)
      })

      return {
        xAixisList,
        values: {
          data: values,
          markPointData
        },
        actualGas
      }
    },
    /**
     * @msg: 获取指数走势图数据
     * @param {type}
     * @return:
     */
    getMonthData() {
      const { meterId } = this.options
      getCandlestickData({
        meterId,
        month: this.zhishuAddDate
      }).then(res => {
        this.$Spin.hide()
        if (!this.hasZhishuRequest) return
        if (res.date && res.date.length > 0) {
          const { xAixisList, values = {}, actualGas } = this.modifyRectTreeMapData(res.date)
          let _currentCanleData = null
          if (!isEmpty(this.rectTreeMapData)) {
            _currentCanleData = this.rectTreeMapData
          } else {
            _currentCanleData = {
              xAxis: {
                data: []
              },
              series: [
                {
                  data: [],
                  markPoint: {
                    data: []
                  }
                },
                {
                  data: []
                }
              ]
            }
          }
          const {
            xAxis: { data = [] },
            series = []
          } = _currentCanleData

          this.rectTreeMapData = merge({}, eCandlestickOptions, {
            xAxis: {
              data: concat(xAixisList, data || [])
            },
            series: [
              {
                data: concat(values.data, series[0] ? series[0].data : []),
                markPoint: {
                  data: concat(values.markPointData, series[0].markPoint ? series[0].markPoint.data : [])
                }
              },
              {},
              {},
              {
                data: concat(actualGas, series[3] ? series[3].data : [])
              }
            ]
          })
        } else {
          this.$Spin.hide()
          this.hasZhishuRequest = false
        }
      })
    },
    /**
     * @msg: 每小时抄表周期数据整理
     * @param {type}
     * @return:
     */
    modifyMeterDetailByTimeData(data) {
      const _serList = []
      const _xAxisList = []
      each(data, item => {
        const { collectDataTime, collectValue } = item
        _serList.push({
          name: collectDataTime,
          value: collectValue
        })
        _xAxisList.push(collectDataTime)
      })

      this.zhexianTimeData = merge({}, eLineByTimeOptions, {
        xAxis: {
          data: _xAxisList
        },
        series: [
          {
            data: _serList
          }
        ]
      })
    },
    /**
     * @msg: 获取每小时的抄表周期详情
     * @param {type}
     * @return:
     */
    getMeterDetailByTime(collectDataTime) {
      this.$Loading.start()
      const { meterId } = this.options
      getElineByHours({
        meterId,
        collectDataTime
      }).then(res => {
        this.$Loading.finish()
        if (res.date) {
          this.showMeterTimeModel = true
          this.modifyMeterDetailByTimeData(res.date)
        }
      })
    },
    /**
     * @msg: 点击上证指数图
     * @param {type}
     * @return:
     */
    candlestickClickHandle(data = {}) {
      if (data.seriesType !== 'line') {
        const { meterId } = this.options
        const { name } = data
        this.currentZhishuDate = name
        this.fetchZhexianByDayData({
          meterId,
          days: data.name
        })
      }
    },
    /**
     * @msg: 天数折线图点击
     * @param {type}
     * @return:
     */
    zhexianDayClickHandle(params = {}) {
      const { data = {} } = params
      const { hour } = data
      const date = this.currentZhishuDate + ' ' + hour
      const retData = dayjs(date).format('YYYY-MM-DD HH')
      this.getMeterDetailByTime(retData)
    },
    /**
     * @msg: 指数图生成曲线
     * @param {type}
     * @return:
     */
    createLine() {
      const { series } = this.rectTreeMapData
      const { data = [], name } = series[0]
      const firstList = []
      const twoList = []
      each(data, item => {
        const { value } = item
        firstList.push({
          name,
          value: value[2]
        })
        twoList.push({
          name,
          value: value[3]
        })
      })

      this.$set(this.canlestickData.series, 2, {
        ...series[2],
        data: firstList
      })
      this.$set(this.canlestickData.series, 3, {
        ...series[3],
        data: twoList
      })
    }
  }
}
</script>
<style lang="less" scoped>
@import './index.less';
</style>
